package com.woniu.movie.controller;

import com.woniu.common.result.Result;
import com.woniu.common.entity.Movie;
import com.woniu.common.entity.vo.MovieVo;
import com.woniu.movie.service.IMovieService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mane
 * @since 2025-03-29
 */
@RestController
@RequestMapping("/api/movies")
public class MovieController {

    private static final Logger log = LoggerFactory.getLogger(MovieController.class);
    @Autowired
    private IMovieService movieService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取所有movie
     * @return
     */
    @GetMapping
    @Cacheable(value = "movies")  // 缓存 key 为 "movies" 的数据
    public Result getMovies() {
        List<MovieVo> movies = movieService.listMovieVo();
        return Result.success(movies);
    }

    /**
     * 根据id查电影
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<MovieVo> getMovieById(@PathVariable Integer id) {
        String redisKey = "movie:" + id;
        // 1. 尝试从Redis获取
        Movie movie = (Movie) redisTemplate.opsForValue().get(redisKey);
        if (movie != null) {
            return Result.success(convertToVo(movie));
        }
        // 2. 查数据库并存入Redis
        movie = movieService.getById(id);
        redisTemplate.opsForValue().set(redisKey, movie, 10, TimeUnit.MINUTES);
        return Result.success(convertToVo(movie));
    }
    private MovieVo convertToVo(Movie movie) {
        if (movie == null) return null;
        MovieVo vo = new MovieVo();
        vo.setId(movie.getId());
        vo.setTitle(movie.getTitle());
        vo.setAvailableSeats(movie.getAvailableSeats());
        vo.setAvailableSeats(movie.getAvailableSeats());
        return vo;
    }

}
